package com.duohe.demo;

import com.duohe.demo.entity.User;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.validation.Valid;

@Controller
public class TestValidator {
    @GetMapping("/test")
    public String showForm(User user){
        return  "form/form";
    }
    @GetMapping("/results")
    public String results(){
        return "form/results";
    }

    @PostMapping("/test")
    public String checkUser(@Valid User user, BindingResult bindingResult, RedirectAttributes attr){
        //特别注意，实体中熟悉都必须被验证过，否则不会成功

        if (bindingResult.hasErrors()){
            return "form/form";
        }
        attr.addFlashAttribute("user",user);

        //redirect防止重复提交
        return "redirect:/results";
    }
}
